package com.xiaolin.oa.utils;

import com.xiaolin.oa.enums.BuCode;
import com.xiaolin.oa.exception.ServiceException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author xiaolin
 * @description 业务编号生成器
 * @since 2024/9/4
 */
@Component
public class SerialNumberGenerator {
    @Autowired
    private RedissonClient redissonClient;
    private final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    /**
     * 业务吗
     *
     * @param buCode
     * @return
     */
    public String generateNumber(BuCode buCode) {
        RLock lock = redissonClient.getLock(buCode.getCode());
        if (lock.tryLock()) {
            String number = "";
            try {
                switch (buCode) {
                    case OVERTIME:
                        number = generateOvertimeNumber(buCode.getCode());
                        break;
                    default:
                        ServiceException.error("未定义业务编号生成规则");
                        break;
                }
            } finally {
                lock.unlock();
            }
            return number;
        } else {
            ServiceException.error("编号生成失败");
            return "";
        }
    }

    private String generateOvertimeNumber(String buCode) {
        String number = buCode + "-" + FORMATTER.format(LocalDateTime.now());
        try {
            Thread.sleep(1L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return number;
    }
}
